<template>
  <div class="app-container">
    <div v-if="device !== 'mobile'">
      <el-tabs type="border-card">
        <el-tab-pane>
          <span slot="label"><i class="el-icon-date"></i> 我的行程</span>
          我的行程
        </el-tab-pane>
        <el-tab-pane label="消息中心">消息中心</el-tab-pane>
        <el-tab-pane label="角色管理">角色管理</el-tab-pane>
        <el-tab-pane label="定时任务补偿">定时任务补偿</el-tab-pane>
      </el-tabs>

      <!-- 添加或修改发版值班人员对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="一级组别" prop="dutyFirstLevelGroup">
            <el-input v-model="form.dutyFirstLevelGroup" placeholder="请输入一级组别" />
          </el-form-item>
          <el-form-item label="二级组别" prop="dutySecondLevelGroup">
            <el-input v-model="form.dutySecondLevelGroup" placeholder="请输入二级组别" />
          </el-form-item>
          <el-form-item label="值班测试人员" prop="dutyDevTestId">
            <el-input v-model="form.dutyDevTestId" placeholder="请输入值班测试人员" />
          </el-form-item>
          <el-form-item label="值班关联的发版id" prop="dutyFbId">
            <el-input v-model="form.dutyFbId" placeholder="请输入值班关联的发版id" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>


    <div v-if="device === 'mobile'">
      <van-row type="flex" justify="center" v-if="!readOnly">
        <van-col span="8">
          <van-button round style="width: 100%" type="primary" size="small" icon="add-o" @click="addPerson">新增人员</van-button>
        </van-col>
<!--        <van-col span="1"></van-col>-->
<!--        <van-col span="7">-->
<!--          <van-button round style="width: 100%" type="info" size="small" icon="sign" @click="saveDuty">保存</van-button>-->
<!--        </van-col>-->
        <van-col span="2"></van-col>
        <van-col span="8">
          <van-button round style="width: 100%" type="default" size="small" icon="close" @click="cancelAndClose">返回</van-button>
        </van-col>
      </van-row>
      <van-row type="flex" justify="center" v-if="readOnly">
          <van-button round block style="width: 100%" type="default" size="small" icon="close" @click="cancelAndClose">返回</van-button>
      </van-row>
      <van-tabs v-model="mobilePluginsProp.tabsActive" @change="refreshDutyList">
        <van-tab v-for="item in firstLvGroupList" :title="item" :badge="firstLvPersonCount.hasOwnProperty(item) ? firstLvPersonCount[item] : 0">
          <div class="cate-list">
            <div class="left-nav">
              <van-sidebar v-model="mobilePluginsProp.secondActiveKeyMap[item]" @change="refreshDutyList">
<!--                <van-sidebar-item v-for="item1 in secondLvGroupList[item]" :title="item1.name" :badge="dutyListMap.hasOwnProperty(item1.pkId) ? (dutyListMap[item1.pkId]).length : 0" />-->
                <van-sidebar-item v-for="item1 in secondLvGroupList[item]" :title="item1.name" :badge="secondLvPersonCount.hasOwnProperty(item1.pkId) ? secondLvPersonCount[item1.pkId] : 0" />
              </van-sidebar>
            </div>
            <div class="cate-body">
              <van-divider v-if="currDutyList.length == 0">暂无人员信息</van-divider>
              <van-swipe-cell v-for="(item2, idx) in currDutyList" v-if="currDutyList.length > 0">
                <van-divider>人员{{ idx + 1 }}</van-divider>
                <van-card>
                  <template #tags>
<!--                    <van-cell-group>-->
                      <van-cell :title="'研发：' + formatDutyUser(item2.devUser) + formatDutyType(item2.devDutyType)" />
                      <van-cell :title="'手机号：' + formatDutyPhonenumber(item2.devUser)" />
                      <van-cell :title="'测试：' + formatDutyUser(item2.testUser) + formatDutyType(item2.testDutyType)" />
                      <van-cell :title="'手机号：' + formatDutyPhonenumber(item2.testUser)" />
<!--                    </van-cell-group>-->
                  </template>
                </van-card>

                <template #right v-if="!readOnly">
                  <van-button square type="primary" text="修改" @click="editPerson(idx)" icon="edit" />
                  <van-button square type="danger" text="删除" @click="deletePerson(idx)" icon="close" />
                </template>
              </van-swipe-cell>
            </div>
          </div>


        </van-tab>
      </van-tabs>

      <van-dialog v-model="mobilePluginsProp.showPersonDialog" :title="mobilePluginsProp.dialogTitle" :showCancelButton="true" :showConfirmButton="false" style="height: 90%; overflow-y: auto">
        <van-form validate-first @submit="onSubmitMobileForm">
          <van-field-select-picker
            v-model="personObj.devUserId"
            label="研发值班人"
            placeholder="点击选择研发值班人"
            :columns="userList"
            :option="{label:'nickName',value:'userId'}"
            :isSearch="true"
            @confirm="onConfirmDevUser"
          />
          <van-field
            name="联系电话"
            label="联系电话"
            readonly
            placeholder="选择联系人后自动带出"
            v-model="devUserPhonenumber"
          />
          <van-field-select-picker
            v-model="personObj.devDutyType"
            label="研发值班类型"
            placeholder="点击选择值班类型"
            :columns="dict.type.yjcz_duty_type"
            :option="{label:'label',value:'value'}"
          />
          <van-field-select-picker
            v-model="personObj.testUserId"
            label="测试值班人"
            placeholder="点击选择测试值班人"
            :columns="userList"
            :option="{label:'nickName',value:'userId'}"
            :isSearch="true"
            @confirm="onConfirmTestUser"
          />
          <van-field
            name="联系电话"
            label="联系电话"
            readonly
            placeholder="选择联系人后自动带出"
            v-model="testUserPhonenumber"
          />
          <van-field-select-picker
            v-model="personObj.testDutyType"
            label="测试值班类型"
            placeholder="点击选择值班类型"
            :columns="dict.type.yjcz_duty_type"
            :option="{label:'label',value:'value'}"
          />
          <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </van-dialog>

    </div>

  </div>
</template>

<script>
import {
  listDutyPerson,
  getDutyPerson,
  delDutyPerson,
  addDutyPerson,
  updateDutyPerson,
  listUser, getPersonListByFbId, savePersonList
} from "@/api/yjcz/dutyPerson";
import {mapState} from "vuex";
import VanFieldSelectPicker from "@/components/VantTools/VanFieldSelectPicker";
import {Dialog, Notify} from "vant";
import {addFbDuty, delFbDuty, updateFbDuty} from "@/api/yjcz/fbDuty";
import DutyPerson from "@/layout/mixin/DutyPerson";

export default {
  name: "DutyPerson",
  mixins: [DutyPerson],
  computed: {
    ...mapState({
      device: state => state.app.device,
    })
  },
  components: {VanFieldSelectPicker},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发版值班人员表格数据
      dutyPersonList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dutyFirstLevelGroup: null,
        dutySecondLevelGroup: null,
        dutyDevUserId: null,
        dutyDevTestId: null,
        dutyFbId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

      currEditPersonIdx: -1,
      personObj: {},
      devUserPhonenumber: '',
      testUserPhonenumber: '',
      currFbId: '',
      mobilePluginsProp: {
        tabsActive: '',
        secondActiveKeyMap: {},
        showPersonDialog: false,
        dialogTitle: '新增值班人员'
      },
      readOnly: false
    };
  },
  created() {
    this.getUserList()
    // this.getList();
    let fbId = this.$route.query.fbId
    let readOnly = this.$route.query.readOnly
    this.readOnly = Number(readOnly) === 1
    this.currFbId = fbId
    if (fbId) {
      getPersonListByFbId(fbId).then(response => {
        if (response.code === 200) {
          let data = response.data
          this.parseDataList(data)
          this.refreshDutyList()
        } else {
          Notify({ type: 'danger', message: response.msg });
        }
      })
    } else {
      Notify({ type: 'danger', message: '没有发版信息，无法进行任何操作' });
    }
  },
  methods: {

    onConfirmDevUser (row) {
      this.devUserPhonenumber = row.phonenumber
      this.personObj.devUserId = row.userId
      this.personObj.devUser = row
    },
    onConfirmTestUser (row) {
      this.testUserPhonenumber = row.phonenumber
      this.personObj.testUserId = row.userId
      this.personObj.testUser = row
    },

    addPerson () {
      if (!this.currFbId) {
        Notify({ type: 'danger', message: '没有发版信息，无法进行任何操作' });
        return
      }
      this.devUserPhonenumber = this.testUserPhonenumber = ''
      this.currEditPersonIdx = -1
      this.personObj = {
        fbId: this.currFbId,
        dutyPersonId: this.currSecondLvObj.pkId
      }
      this.mobilePluginsProp.dialogTitle = '新增值班人员'
      this.mobilePluginsProp.showPersonDialog = true
    },
    cancelAndClose () {
      this.close()
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: "/yjcz/fbInfo"};
      this.$tab.closeOpenPage(obj);
    },
    editPerson (idx) {
      this.currEditPersonIdx = idx
      this.personObj = JSON.parse(JSON.stringify(this.dutyListMap[this.currSecondLvObj.pkId][idx]))
      let devUser = this.personObj.devUser
      this.devUserPhonenumber = devUser ? devUser.phonenumber : ''
      let testUser = this.personObj.testUser
      this.testUserPhonenumber = testUser ? testUser.phonenumber : ''
      this.mobilePluginsProp.dialogTitle = '修改值班人员'
      this.mobilePluginsProp.showPersonDialog = true
    },
    deletePerson (idx) {
      Dialog.confirm({
        title: '确认删除',
        message: '是否确认删除发版值班人员？',
      }).then(() => {
        // on confirm
        let personObj = this.currDutyList[idx]
        return delFbDuty(personObj.pkId);
      }).then(() => {
        Notify({ type: 'success', message: '删除成功' });
        let dutyList = this.dutyListMap[this.currSecondLvObj.pkId]
        dutyList.splice(idx, 1)
        this.currDutyList = JSON.parse(JSON.stringify(dutyList))
      })
    },
    onSubmitMobileForm () {
      let devUserId = this.personObj.devUser
      let testUserId = this.personObj.testUser
      if (!devUserId && !testUserId) {
        Notify({ type: 'danger', message: '研发测试人员请至少选择一个' });
        return
      }
      if (!devUserId) {
        this.personObj.devDutyType = null
      }
      if (!testUserId) {
        this.personObj.testDutyType = null
      }
      let dutyList = this.dutyListMap[this.currSecondLvObj.pkId]
      if (!this.personObj.pkId) {
        addFbDuty(this.personObj).then(response => {
          if (response.code === 200) {
            this.personObj.pkId = response.data
            if (!dutyList) {
              dutyList = this.dutyListMap[this.currSecondLvObj.pkId] = []
            }
            dutyList.push(this.personObj)
            this.currDutyList = JSON.parse(JSON.stringify(dutyList))
            this.mobilePluginsProp.showPersonDialog = false
          } else {
            Notify({ type: 'danger', message: response.msg });
          }
        })
      } else {
        updateFbDuty(this.personObj).then(response => {
          if (response.code === 200) {
            dutyList[this.currEditPersonIdx] = this.personObj
            this.currDutyList = JSON.parse(JSON.stringify(dutyList))
            this.mobilePluginsProp.showPersonDialog = false
          } else {
            Notify({ type: 'danger', message: response.msg });
          }
        })
      }
    },
    refreshDutyList () {
      let dutyList = this.dutyListMap[this.getFirstAndSecondName()]
      this.currDutyList = dutyList ? dutyList : []
    },
    getFirstAndSecondName () {
      let firstLvIdx = this.mobilePluginsProp.tabsActive
      if (firstLvIdx === '') {
        firstLvIdx = this.mobilePluginsProp.tabsActive = 0
      }
      let firstName = this.currFirstLvName = this.firstLvGroupList[firstLvIdx]
      let secondIdx = this.mobilePluginsProp.secondActiveKeyMap[firstName]
      if (secondIdx === undefined) {
        secondIdx = this.mobilePluginsProp.secondActiveKeyMap[firstName] = 0
      }
      this.currSecondLvObj = this.secondLvGroupList[firstName][secondIdx]
      return this.currSecondLvObj.pkId
    },

    /** 查询发版值班人员列表 */
    getList() {
      this.loading = true;
      listDutyPerson(this.queryParams).then(response => {
        this.dutyPersonList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pkId: null,
        dutyFirstLevelGroup: null,
        dutySecondLevelGroup: null,
        dutyDevUserId: null,
        dutyDevTestId: null,
        dutyFbId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.pkId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加发版值班人员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const pkId = row.pkId || this.ids
      getDutyPerson(pkId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改发版值班人员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.pkId != null) {
            updateDutyPerson(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDutyPerson(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const pkIds = row.pkId || this.ids;
      this.$modal.confirm('是否确认删除发版值班人员编号为"' + pkIds + '"的数据项？').then(function() {
        return delDutyPerson(pkIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('yjcz/dutyPerson/export', {
        ...this.queryParams
      }, `dutyPerson_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
table {
  border-collapse: collapse;
}

td, th {
  border: 1px solid black;
  padding: 10px;
  text-align: center;
  width: 200px;
}
caption {
  font-weight: bold;
  text-align: center;
  color: red;
}

.cate-list {
  display: flex;
}
.left-nav {
  width: 28%;
  height: calc(100vh - 180px);
  overflow: auto;
}
.cate-body {
  width: 72%;
  height: calc(100vh - 180px);
  overflow: auto;
}
</style>
